# coding=utf-8
"""
查询休眠唤醒
"""
import logging

import datetime
import pymongo
from pymongo import MongoClient

from dbtool import MysqlMgr
from logmod import LogMgr

""" mongo configure """
#mongoUrl = 'mongodb://gps:gps@192.168.1.62/?authSource=gps'
mongo_url_ali = 'mongodb://gps:gps@localhost:37017/?authSource=gps'
db_name = 'gps'

config_ali = {'host': '127.0.0.1',  # 默认127.0.0.1
              'user': 'jsecode',
              'password': 'jsecode123',
              'port': 13306,  # 默认即为3306
              'database': 'rescue_platform_data',
              'charset': 'utf8'  # 默认即为utf8
              }

""" logging configure """
logger = LogMgr.getLogger('mongo')
logger.setLevel(logging.DEBUG)

def query_deviceinfo_mysql(**kwargs):
    """
    查询设备信息
    :param args:
    :param kwargs: 配置信息
    :return: list of (device_no, VEH_ID, DEVICE_TYPE,...)
    """
    cnn = MysqlMgr.Database(**kwargs)
    sqlQuery = 'select device_no, VEH_ID, DEVICE_TYPE from device_info order by device_no'
    result = cnn.fetch_all(sqlQuery, None)
    #print result

    cnn.close()
    return result

def query_sleep_from_mongo(db, deviceid):
    """
    查询一个设备的信息
    :return: list of []
    """
    collection = db['gps201607']
    cursor = collection.find(filter={'devid': deviceid, 'eventEx.eventType':{'$gte':1}},
                         projection={'_id': False, 'devid': True, 'hostid': True, 'time': True,
                                     'lat': True, 'lon': True, 'alt': True, 'speed': True,
                                     'ang': True, 'acc': True, 'rectm': True, 'gwid': True, 'type': True,
                                     'eventEx':True})
    cursor.sort([ ('rectm', pymongo.ASCENDING) ])

    result = []

    for obj in cursor:
        result.append(obj)
        # print  type(obj)
        #logger.debug(obj)
    cursor.close()

    return result

def cal_diff(v1, v2):
    # 计算两个时间的差值
    return (v2 - v1).seconds

def utc_local(utc):
    return utc + datetime.timedelta(hours=8)

def parse_sleep_one(db, deviceid):
    gps_list = query_sleep_from_mongo(db, deviceid)
    #logger.info(gps_list)
    for index in xrange(0, len(gps_list)):
        # logger.info("%s, %s, %s, %s" %
        #             (gps_list[index]['devid'], utc_local(gps_list[index - 1]['rectm']).strftime("%Y-%m-%d %H:%M:%S"),
        #              utc_local(gps_list[index]['rectm']).strftime("%Y-%m-%d %H:%M:%S"),
        #              diff / 60))
        #logger.info(gps_list[index])
        if index == 0:
            diff = 0
        else:
            diff = cal_diff(gps_list[index - 1]['rectm'], gps_list[index]['rectm'])
            diff = round(diff/60.0, 1)
        gps = gps_list[index]
        if (gps['eventEx']['eventType'] == 2) :
            logger.info("%s, %s, %s, %s, %s, %s" % (
                gps['devid'], utc_local(gps['time']), utc_local(gps['rectm']), diff, gps['eventEx']['eventType'], gps['eventEx']['detail']['reason'])
                        )
        else :
            logger.info("%s, %s, %s, %s, %s, %s" % (
                gps['devid'], utc_local(gps['time']), utc_local(gps['rectm']), diff, gps['eventEx']['eventType'], None)
                     )

def query_sleep():
    client = MongoClient(mongo_url_ali)
    db = client[db_name]

    devicelist = query_deviceinfo_mysql(**config_ali)
    # parse_sleep_one(db, '3870010001')
    for devid_info in devicelist:
        parse_sleep_one(db, devid_info[0])

    client.close()

if __name__ == '__main__':
    query_sleep()